/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.usefullc.proxy.test.proxy;

import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLEngine;

public class HexDumpProxyInitializer extends ChannelInitializer<SocketChannel> {

    private final String remoteHost;
    private final int remotePort;
    private SslContext sslContext;


    public HexDumpProxyInitializer(String remoteHost, int remotePort, SslContext sslContext) {
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
        this.sslContext = sslContext;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ch.pipeline().addLast(
                new LoggingHandler(LogLevel.INFO),
                new HexDumpProxyFrontendHandler(remoteHost, remotePort));
        if(sslContext != null){
            SSLEngine engine = sslContext.newEngine(ch.alloc());
            engine.setUseClientMode(false);
            engine.setNeedClientAuth(false);
            ch.pipeline().addFirst(new SslHandler(engine));
        }
    }

    public static void main(String[] args) {
        String code = "47455420687474703a2f2f7777772e78756578696c692e636f6d2f696d616765732f6a732f756172656469726563742e6a7320485454502f312e310d0a486f73743a207777772e78756578696c692e636f6d0d0a557365722d4167656e743a206375726c2f372e36342e310d0a4163636570743a202a2f2a0d0a50726f78792d436f6e6e656374696f6e3a204b6565702d416c6976650d0a0d0a";
        byte[] bytes = ByteBufUtil.decodeHexDump(code);
        System.out.println(new String(bytes));
    }
}
